package com.zq.ht.web.service.content;

import com.baomidou.mybatisplus.plugins.Page;
import com.zq.ht.common.util.PageUtil;
import com.zq.ht.dao.TAttachmentMapper;
import com.zq.ht.dao.TNewsMapper;
import com.zq.ht.model.TAttachment;
import com.zq.ht.model.TNews;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.List;

/**
 * Created by admin on 2016/6/21.
 */
@Service
public class NewsService {
    @Autowired
    private TNewsMapper newsMapper;
    @Autowired
    private TAttachmentMapper attachmentMapper;


    public PageUtil getNewsList(PageUtil pageUtil){
        Page page = new Page(pageUtil.getRowStart()+1,pageUtil.getRowCount());
        List listAll = newsMapper.selectList(RowBounds.DEFAULT,null);
        pageUtil.setTotalRows(listAll.size());
        List list = newsMapper.selectList(page,null);
        pageUtil.setResults(list);
        return pageUtil;
    }

    public void saveNews(TNews news, String content) {
        TAttachment attachment = new TAttachment();
        attachment.setType(0);
        attachment.setContent(content.getBytes());
        attachmentMapper.insert(attachment);

        news.setContentId(attachment.getId());
        newsMapper.insert(news);
    }

    public void updateNews(TNews news, String content){

        TAttachment attachment = attachmentMapper.selectById((long)news.getContentId());
        attachment.setContent(content.getBytes());
        attachmentMapper.updateById(attachment);

        newsMapper.updateById(news);
    }

    public void deleteNews(long id) {
        TNews news = newsMapper.selectById(id);
        attachmentMapper.deleteById((long)news.getContentId());
        newsMapper.deleteById(id);
    }

    public void getNewsById(long id, ModelMap map) {
        TNews news = newsMapper.selectById(id);
        TAttachment attac = attachmentMapper.selectById((long)news.getContentId());
        news.setContentId(attac.getId());
        map.put("news",news);
        map.put("content",new String(attac.getContent()));
    }
}
